<?php
namespace app\index\controller;

use app\BaseController;
use app\index\controller\UserToken;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use think\facade\View;

class Index extends BaseController
{
    public function index(): string
    {
        echo "hello world";exit;
        $name = "林";
        View::assign([
            'name' => $name,
        ]);
        return View::fetch();
    }


    /**
     * 生成密码
     * @return void
     */
    public function getGeneratorPassWord()
    {
        $postData = $this->request->param();
        checkPostData($postData);
        if(empty($postData['passWordLength'])){
            isFail("请选择密码长度");
        }

        if(empty($postData['checkList'])){
            isFail("至少勾选一项");
        }
        $checkList = json_decode($postData['checkList'], true);
        if(!is_array($checkList) || count($checkList)==0){
            isFail('至少勾选一项');
        }

        $password = "";
        $randStr = "";

        $number = "0123456789";
        $lowerCaseStr = "abcdefghijklmnopqrstuvwxyz";
        $upperCaseStr = strtoupper($lowerCaseStr);
        $specialStr = "~!@#$%^&*()_+-=";

        //数字
        if(in_array(1, $checkList)){
            $randStr .= $number;
        }

        //大写字母
        if(in_array(2, $checkList)){
            $randStr .= $upperCaseStr;
        }

        //小写字母
        if(in_array(3, $checkList)){
            $randStr .= $lowerCaseStr;
        }

        //特殊字符
        if(in_array(4, $checkList)){
            $randStr .= $specialStr;
        }

        $randArr = str_split($randStr);
        for($i = 0; $i <$postData['passWordLength']; $i++){
            $password .= $randArr[rand(0, count($randArr)-1)];
        }
        isSuccess('请求成功', ['password'=>$password]);
    }


    /**
     * 保存密码
     * @return void
     */
    public function savePassword()
    {
        $postData = $this->request->param();
        checkPostData($postData);
        $userId = (new UserToken($this->app))->getUserId();
        $result = Db::name('password')->save([
            'password'=>$postData['password'],
            'create_time'=>getCurrentTime(),
            'user_id' => $userId
        ]);
        if(!$result){
            isFail('保存失败');
        }
        isSuccess('保存成功');
    }


    /**
     * 复制过的密码列表
     * @return void
     */
    public function getPasswordList()
    {
        $userId = (new UserToken($this->app))->getUserId();
        $postData = $this->request->param();
        $page = (isset($postData['page']) && $postData['page'] >0) ? $postData['page'] : 1;
        $pageSize = (isset($postData['pageSize']) && $postData['pageSize'] >0) ? $postData['pageSize'] : 20;

        $list = Db::name('password')->field('id,password')->where([
            'is_delete'  => 0,
            'user_id'  => $userId,
        ])->order('id', 'desc')->page($page, $pageSize)->select()->toArray();
        isSuccess('请求成功', $list);
    }

    /**
     * 删除密码
     * @return void
     */
    public function delPassword()
    {
        $postData = $this->request->param();
        checkPostData($postData);
        $result = Db::name('password')->where(['id'=>$postData['id']])->update(['is_delete'=>1]);
        if($result){
            isSuccess('删除成功');
        }else{
            isFail('删除失败');
        }
    }

    /**
     * 生成随机数
     * @return void
     */
    public function getRandomNumber()
    {
        $postData = $this->request->param();
        checkPostData($postData);

        $minNumber = ($postData['minNumber'] || $postData['minNumber']==0) ? $postData['minNumber'] : 0;
        $maxNumber = ($postData['maxNumber'] || $postData['maxNumber']==0) ? $postData['maxNumber'] : 100;
        $decimal = $postData['decimalPlaces'] ? : 0;

        $reg = "/^[1-9][0-9]*$/";

        if(!(preg_match($reg, $minNumber) || $minNumber ==0)){
            isFail("最小值取值有误");
        }

        if(!(preg_match($reg, $maxNumber) || $maxNumber ==0)){
            isFail("最大值取值有误");
        }

        if($minNumber >= $maxNumber || ($minNumber==0 && $maxNumber==0)){
            isFail("取值范围有误");
        }

        if($decimal >5){
            isFail("小数点不能超过5位");
        }

        if($decimal !=0){
            $randomNumber = mt_rand($minNumber, $maxNumber-1);
            $decimalPart = number_format((mt_rand() / mt_getrandmax()), $decimal);
            $randomNumber = (int)$randomNumber + $decimalPart;
        }else{
            $randomNumber = mt_rand($minNumber, $maxNumber);
        }
        isSuccess('获取成功', ['randomNumber'=>floatval($randomNumber)]);

    }


    public function getCode2Session()
    {
        $postData = $this->request->param();
        checkPostData($postData);

        $code = $postData['code'];
        $result = (new WxappApi($this->app))->jscode2session($code);
        if(isset($result['errcode']) && $result['errcode'] != 0){
            isFail($result['errmsg']);
        }


        //检测openid
        $checkResult = Db::name('user')->field('id')->where(['openid'=>$result['openid'], 'is_delete'=>0])->find();
        if($checkResult){
            $user_id = $checkResult['id'];
        }else{
            $user_id = Db::name('user')->insertGetId([
                'openid' => $result['openid'],
                'create_time' => getCurrentTime(),
            ]);

            if(!$user_id){
                isFail("添加失败");
            }
        }

        isSuccess("请求成功", [
            'user_id' => $user_id,
            'session_key' => $result['session_key'],
            'token' => getAuthCode($user_id),
        ]);
    }

}
